<script lang="ts">
	import type { PlanInfo } from '$lib/api/proto/roadmap_plan_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import EditorJS from '@editorjs/editorjs';
	import { DatePicker } from '@svelte-plugins/datepicker';
	import moment from 'moment';

	interface Props {
		plan?: PlanInfo;
		roadmapId: string;
		memberUserId: string;
		onCancel: () => void;
		onOk: () => void;
	}
	let props: Props = $props();

	let planName = $state(props.plan?.basicInfo?.planName ?? '');
	let descEditor: EditorJS | null = $state(null);
	let startTime = $state(moment().add(1, 'days').startOf('day').valueOf());
	let endTime = $state(moment().add(11, 'days').endOf('day').valueOf());

	async function addPlan() {
		if (userStore.userSession == null || descEditor == null) {
			return;
		}

		const descData = await descEditor.save();

		await callApi(
			appStore.roadmapPlanApiClient.addPlan({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.memberUserId,
				basicInfo: {
					planName: planName,
					planDesc: JSON.stringify(descData)
				},
				startTime: BigInt(startTime),
				endTime: BigInt(endTime)
			}).response
		);

		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '创建成长计划成功',
			keepTime: 2000
		});
	}

	async function updatePlan() {
		if (userStore.userSession == null || descEditor == null || props.plan == undefined) {
			return;
		}

		const descData = await descEditor.save();
		console.log(descData);

		await callApi(
			appStore.roadmapPlanApiClient.updatePlan({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.memberUserId,
				planId: props.plan.planId,
				basicInfo: {
					planName: planName,
					planDesc: JSON.stringify(descData)
				}
			}).response
		);

		props.onOk();
		appStore.addToastMessage({
			level: 'success',
			content: '修改成长计划成功',
			keepTime: 2000
		});
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box w-[800px] max-w-none">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onCancel()}>✕</button
		>
		<h3 class="text-lg font-bold">
			{props.plan == undefined ? '创建成长计划' : '修改成长计划'}
		</h3>
		<div class="max-h-[60vh] overflow-y-auto pr-[10px] flex-col space-y-4 pt-[20px]">
			<label class="label w-full">
				<span class="label w-[80px] text-right inline-block pr-[10px]">名称:</span>
				<input type="text" class="input w-full" bind:value={planName} />
			</label>
			{#if props.plan == undefined}
				<h4 class="text-base font-bold">时间区间</h4>
				<div class="flex justify-center">
					<DatePicker
						theme="plan"
						startDate={startTime}
						endDate={endTime}
						isOpen
						isRange
						isMultipane
						showYearControls
						alwaysShow
						enablePastDates
						enableFutureDates
						startOfWeek={1}
						dowLabels={['日', '一', '二', '三', '四', '五', '六']}
						monthLabels={[
							'一月',
							'二月',
							'三月',
							'四月',
							'五月',
							'六月',
							'七月',
							'八月',
							'九月',
							'十月',
							'十一月',
							'十二月'
						]}
						style=""
						onDateChange={(e: { startDate: number; endDate: number }) => {
							startTime = moment(e.startDate).startOf('day').valueOf();
							endTime = moment(e.endDate).endOf('day').valueOf();
						}}
					/>
				</div>
			{/if}
			<h4 class="text-base font-bold">成长计划说明</h4>
			<SimpleEditor
				sizeClass="min-h-[300px] border-2 border-base-200 max-h-[300px]"
				data={props.plan?.basicInfo?.planDesc}
				placeholder="请输入成长计划说明"
				onInit={(tmpEditor) => (descEditor = tmpEditor)}
			/>
		</div>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button
				class="btn btn-primary"
				disabled={planName.trim() == ''}
				onclick={() => {
					if (props.plan == undefined) {
						addPlan();
					} else {
						updatePlan();
					}
				}}>{props.plan == undefined ? '创建' : '修改'}</button
			>
		</div>
	</div>

	<div class="modal-backdrop">
		<button onclick={() => props.onCancel()}>close</button>
	</div>
</dialog>

<style>
	:global(.datepicker[data-picker-theme='plan']) {
		--datepicker-container-background: var(--color-base-100);
		--datepicker-container-border: none;
		--datepicker-container-position: none;
		--datepicker-container-box-shadow: none;
		--datepicker-calendar-range-selected-background: var(--color-accent);
		--datepicker-calendar-range-background: var(--color-base-200);
		--datepicker-calendar-range-start-box-shadow: inset -20px 0 0 var(--color-accent);
		--datepicker-calendar-range-end-box-shadow: inset 20px 0 0 var(--color-accent);
		--datepicker-calendar-day-color: var(--color-base-content);
		--datepicker-calendar-day-color-disabled: var(--color-base-300);
		--datepicker-calendar-day-color-hover: var(--color-base-content);
		--datepicker-calendar-day-background-hover: var(--color-base-200);
	}
</style>
